package com.dongfang.coa;

import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;

/**
 * 方向
 * 
 * @author dongfang
 * 
 */
public class OrientationActivity extends Activity implements SensorEventListener {
	TextView textView;
	StringBuilder builder = new StringBuilder();
	float yaw;
	float pitch;
	float roll;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		textView = new TextView(this);
		setContentView(textView);

		SensorManager manager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

		if (manager.getSensorList(Sensor.TYPE_ORIENTATION).size() == 0) {
			textView.setText("No orientation installed");
		}
		else {
			Sensor compass = manager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
			if (!manager.registerListener(this, compass, SensorManager.SENSOR_DELAY_GAME)) {
				textView.setText("Couldn't register sensor listener");
			}
		}
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {}

	@Override
	public void onSensorChanged(SensorEvent event) {
		yaw = event.values[0];
		pitch = event.values[1];
		roll = event.values[2];

		calculateOrientation();
	}

	public void calculateOrientation() {
		builder.setLength(0);
		builder.append("偏航角即与地球磁场方向的偏角yaw: ");
		builder.append(yaw + "\n");
		builder.append("手机的俯仰角pitch: ");
		builder.append(pitch + "\n");
		builder.append("手机的翻转角 roll: ");
		builder.append(roll);
		textView.setText(builder.toString());
	}

}
